package com.ddone.exception;

import com.ddone.model.vo.Result;
import com.ddone.model.vo.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

/**
 * @author ddone
 * @date 2024/3/27-18:49
 */
@RestControllerAdvice
@PropertySource(value = "classpath:error.properties")
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private Environment env;

    @ExceptionHandler(Exception.class)
    public Result<Object> error(Exception e) {
        e.printStackTrace();
        return Result.fail();
    }

    @ExceptionHandler(AuthManagerException.class)
    public Result<Object> authManagerError(AuthManagerException e) {
        Integer code = e.getCode();
        String message = Optional.ofNullable(e.getMessage())
                .filter(StringUtils::isNotBlank)
                .orElseGet(() -> env.getProperty(e.getCode() + ""));
        log.error(message);
        e.printStackTrace();
        return Result.fail().message(message).code(code);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Result<Object> accessDeny(Exception e){
        e.printStackTrace();
        return Result.build(null, ResultCodeEnum.PERMISSION);
    }
}
